/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.people;

import java.util.List;

import android.app.ActivityManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.widget.RemoteViews;

/**
 * Simple widget to show a user-selected picture.
 */
public class PhotoAppWidgetProvider extends AppWidgetProvider {
    private static final String TAG = "PhotoAppWidgetProvider";
    private static final boolean DEBUG = false;
    
    private Intent mIntent;
    private PhotoDatabaseHelper mdb;
    
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        int[] ids = mIntent.getIntArrayExtra(SlideImageViewService.WIDGET_IDS);
        long[] fileid = mIntent.getLongArrayExtra(SlideImageViewService.IMAGE_PATHS);
        
        if (ids != null && fileid != null) {
            mdb = new PhotoDatabaseHelper(context);
            for (int index = 0; index < ids.length; ++index) {
                LOGD("^^^^^^ On photo widget update, the id = " + ids[index] 
                           + " filename = " + fileid[index] + " ^^^^^^");
                RemoteViews views = buildUpdate(context, fileid[index], ids[index]);
                appWidgetManager.updateAppWidget(ids[index], views);
            }
        } else {
			Intent intent = new Intent(context, SlideImageViewService.class);
			intent.putExtra(SlideImageViewService.WIDGET_IDS, appWidgetIds);
			context.startService(intent);
        }
    }
        
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        // Clean deleted photos out of our database
        Intent intent = new Intent(SlideImageViewService.BCR_DELETE_CLIENT);
        LOGD("******** onDelete id = " + appWidgetIds[0] + " *********");
        intent.putExtra(SlideImageViewService.WIDGET_ID, appWidgetIds[0]);
        context.sendBroadcast(intent);
    }

    public void onReceive(Context context, Intent intent) {
        LOGD(" ========= on receive ========== ");
        if (intent.getAction().equals(SlideImageViewService.ACTION_CLICK_WIDGET) == true) {
            LOGD("===== image view click =======");
            Intent intentSend = new Intent(SlideImageViewService.ACTION_CLICK_WIDGET_SERVICE);
            intentSend.putExtra(SlideImageViewService.WIDGET_ID, 
                            intent.getIntExtra(SlideImageViewService.WIDGET_ID, -1));
            context.sendBroadcast(intentSend);
        } else {
            mIntent = intent;
            super.onReceive(context, intent);
        }
    }
    
    /**
     * Load photo for given widget and build {@link RemoteViews} for it.
     */
    private RemoteViews buildUpdate(Context context, long fileid, int appWidgetId) {
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.photo_frame);
        
//        initGalleryIntent(context, appWidgetId, views, R.id.photo);
        if (fileid != -1) {
            Bitmap bm = mdb.getPhoto(fileid);
            if (bm != null) {
                LOGD("###### get the show image : " + fileid + " from database success! #######");
                views.setImageViewBitmap(R.id.photo, bm);
            }
        } else {
            LOGD("update a empty photo to show");
        }
        return views;
    }
    
    private void initGalleryIntent(Context context, int appWidgetId, RemoteViews views, int viewId) {
        Intent active = new Intent(context.getApplicationContext(), PhotoAppWidgetProvider.class);

        active.setAction(SlideImageViewService.ACTION_CLICK_WIDGET);

        active.putExtra(SlideImageViewService.WIDGET_ID, appWidgetId);
        active.putExtra(SlideImageViewService.CLICK_VIEW_ID, viewId);

        // This is tricky, be aware that you can only have one set of extras for
        // any given PendingIntent action+data+category+component pair.
        active.setData(Uri.parse(appWidgetId + ":" + viewId));

        PendingIntent actionPendingIntent = PendingIntent.getBroadcast(
                context.getApplicationContext(), 0, active, PendingIntent.FLAG_CANCEL_CURRENT);
        views.setOnClickPendingIntent(viewId, actionPendingIntent);
    }
    
    public static void LOGD(String msg) {
        if (DEBUG == true) {
            Log.d(TAG, msg);
        }
    }

}

